//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {

    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        const result = await RES.getResAsync("description_json")
        this.startAnimation(result);
        await platform.login();
        const userInfo = await platform.getUserInfo();
        console.log(userInfo);

    }

    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await RES.loadConfig("resource/default.res.json", "resource/");
            await this.loadTheme();
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    private textfield: egret.TextField;
    private resultBGView: egret.Sprite;
    private moveView: LHBrick;
    private donwX:number;
    private downY:number;
    private originalX:number;
    private originalY:number;
    private addViewArray: Array<LHBrick> = [];
    private checkPointArray: Array<number> = [];

    private scrollViewContent: egret.Sprite;
    private itemBGScrollView: egret.ScrollView;

    private gridSide: number = 100; 
    private col: number = 4;
    private row: number = 4;

    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {

        //场景宽高
        let stageW = this.stage.stageWidth;
        let stageH = this.stage.stageHeight;
        let gridSide = this.gridSide;
        let row = this.row;
        let col = this.col;

        for (var i=0; i<row * col; i++) {
            this.checkPointArray.push(0);
        }

        let topMask = new egret.Shape();
        topMask.graphics.beginFill(0x000000, 1.0);
        topMask.graphics.drawRect(0, 0, stageW, stageH);
        topMask.graphics.endFill();
        this.addChild(topMask);

        //结果背景
        let resultBGView = new egret.Sprite();
        resultBGView.graphics.beginFill(0xffffff, 1.0);
        resultBGView.graphics.drawRect(0, 0, gridSide * row, gridSide * col);
        resultBGView.graphics.endFill();
        resultBGView.y = 200;
        resultBGView.x = (stageW - gridSide * row) / 2;
        this.addChild(resultBGView);
        this.resultBGView = resultBGView;

        //拼图元素
        var itemArr:Array<LHBrickType> = [LHBrickType.NoTopLeft, LHBrickType.NoBottomRight, LHBrickType.NoTopRight,LHBrickType.NoBottomLeft, LHBrickType.All];
        var scrollViewContent = new egret.Sprite();
        this.scrollViewContent = scrollViewContent;

        var itemBGScrollView: egret.ScrollView = new egret.ScrollView(scrollViewContent);
        itemBGScrollView.width = stageW - 100;
        itemBGScrollView.height = 250;
        itemBGScrollView.x = 50;
        itemBGScrollView.y = resultBGView.y + 400 + 10;
        itemBGScrollView.verticalScrollPolicy = "off";
        this.addChild(itemBGScrollView);
        this.itemBGScrollView = itemBGScrollView;

        var itemLeft = 0;
        for (var i=0; i<itemArr.length; i++) {
            //方块
            let item: LHBrick = new LHBrick();
            item.reloadWithStyle(itemArr[i]);
            item.x = itemLeft;
            scrollViewContent.addChild(item);
            this.addViewArray.push(item);

            var itemRight = item.x + item.width + 10

            scrollViewContent.graphics.beginFill(0xffffff, 1.0);
            scrollViewContent.graphics.drawRect(itemLeft, 0, itemRight, 250);
            scrollViewContent.graphics.endFill();

            itemLeft = itemRight;

            item.touchEnabled = true;
            item.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.startMove,this);
            item.addEventListener(egret.TouchEvent.TOUCH_END,this.stopMove,this);
        }
        
        let colorLabel = new egret.TextField();
        colorLabel.textColor = 0xffffff;
        colorLabel.width = stageW;
        colorLabel.textAlign = "center";
        colorLabel.text = "拼图";
        colorLabel.size = 24;
        this.addChild(colorLabel);

        let button = new eui.Button();
        button.label = "重置";
        button.bottom = 0;
        button.horizontalCenter = 0;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onButtonClick, this);
    }

    private resetBrickPoints():void {
        for (var i=0; i<this.addViewArray.length; i++) {
            
        }
    }

private startMove(e:egret.TouchEvent):void{
   //把手指按到的对象记录下来
   this.moveView = e.currentTarget;
   //计算手指和要拖动的对象的距离
   this.donwX = e.localX;
   this.downY = e.localY;
   this.originalX = this.moveView.x;
   this.originalY = this.moveView.y;
   this.moveView.x = e.stageX - e.localX;
   this.moveView.y = e.stageY - e.localY;

   this.addChild(this.moveView);
   this.itemBGScrollView.horizontalScrollPolicy = "off";

   //手指在屏幕上移动，会触发 onMove 方法
   this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE,this.onMove,this);
 }

 private reloadMoveViewPoint(x ,y): void {
     this.moveView.x = x;
     this.moveView.y = y;
 }

 private stopMove(e:egret.TouchEvent) {console.log(22);

    if (this.moveView == null) {
        return ;
    }

   //手指离开屏幕，移除手指移动的监听
   this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE,this.onMove,this);
   //修正位置

    var contentRect: egret.Rectangle = new egret.Rectangle(this.resultBGView.x, this.resultBGView.y, this.resultBGView.width, this.resultBGView.height);
    var movePoint = new egret.Point(this.moveView.x, this.moveView.y);
    //判断点是否在矩形内
    if (!contentRect.containsPoint(movePoint)) {
        this.resetMoveView();
        return ;
    }

    //检测是否合法
    var indexX = parseInt(((this.moveView.x - this.resultBGView.x) / this.gridSide).toString());
    var indexY = parseInt(((this.moveView.y - this.resultBGView.y) / this.gridSide).toString());

    if (indexX >= this.row - 1 || indexY >= this.col - 1) {
        this.resetMoveView();
        return ;
    }

    var pointArr = this.getPointArrayWithIndex(indexX, indexY);
    //是否重叠
    if (!this.moveView.checkPointRight(pointArr)) {
        this.resetMoveView();
        return ;
    }

    this.addMoveView(indexX, indexY);

 }

 private resetMoveView(): void {
    this.scrollViewContent.addChild(this.moveView);
    this.itemBGScrollView.horizontalScrollPolicy = "on";
    this.reloadMoveViewPoint(this.originalX, this.originalY);
    this.moveView = null;
 }

 private addMoveView(indexX, indexY):void {
    this.addViewArray.push(this.moveView);
     
    this.checkPointArray[indexY * this.row + indexX] = this.moveView.pointArray[0];
    this.checkPointArray[indexY * this.row + indexX + 1] = this.moveView.pointArray[1];
    this.checkPointArray[(indexY + 1) * this.row + indexX] = this.moveView.pointArray[2];
    this.checkPointArray[(indexY + 1) * this.row + indexX + 1] = this.moveView.pointArray[3];

    this.resultBGView.addChild(this.moveView);
    this.reloadMoveViewPoint(indexX * this.gridSide, indexY * this.gridSide);
    this.moveView.reloadColorStyle(LHBrickColorStyle.blue);
    this.moveView.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.startMove, this)

    //检测是否成功
    this.checkDone();
    this.itemBGScrollView.horizontalScrollPolicy = "on";
    this.moveView = null;

    for (var i=0;i<this.row; i++) {
        var str = '';

        for (var j=0; j<this.row; j++) {
            str = str + ' ' + this.checkPointArray[i * this.row + j];
        }

        console.log(str);    
    }
    
 }

//检测是否成功
private checkDone():void
{
    for (var i=0; i<this.checkPointArray.length; i++) {
        var num = this.checkPointArray[i];

        if (num == 0) {
            return ;
        }
    }

    //成功
    this.showAlertWithText("拼图成功");
}

private getPointArrayWithIndex(indexX, indexY):Array<number> {
    var arr: Array<number> = [];

    arr.push(this.checkPointArray[indexY * this.row + indexX]);
    arr.push(this.checkPointArray[indexY * this.row + indexX + 1]);
    arr.push(this.checkPointArray[(indexY + 1) * this.row + indexX]);
    arr.push(this.checkPointArray[(indexY + 1) * this.row + indexX + 1]);

    return arr;
}

 private onMove(e:egret.TouchEvent):void{
   //通过计算手指在屏幕上的位置，计算当前对象的坐标，达到跟随手指移动的效果
    var newX = e.stageX - this.donwX;
    var newY = e.stageY - this.downY;
    
    this.reloadMoveViewPoint(newX, newY);
 }

    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string): egret.Bitmap {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
    /**
     * 描述文件加载成功，开始播放动画
     * Description file loading is successful, start to play the animation
     */
    private startAnimation(result: Array<any>): void {
        let parser = new egret.HtmlTextParser();

        let textflowArr = result.map(text => parser.parse(text));
        let textfield = this.textfield;
        let count = -1;
        let change = () => {
            count++;
            if (count >= textflowArr.length) {
                count = 0;
            }
            let textFlow = textflowArr[count];

            // 切换描述内容
            // Switch to described content
            textfield.textFlow = textFlow;
            let tw = egret.Tween.get(textfield);
            tw.to({ "alpha": 1 }, 200);
            tw.wait(2000);
            tw.to({ "alpha": 0 }, 200);
            tw.call(change, this);
        };

        change();
    }

    /**
     * 点击按钮
     * Click the button
     */
    private onButtonClick(e: egret.TouchEvent) {

       this.showAlertWithText("自己手动刷新吧");
    }

    private showAlertWithText(text: string): void {
        let panel = new eui.Panel();
        panel.title = "Title";
        panel.horizontalCenter = 0;
        panel.verticalCenter = 0;
        this.addChild(panel);

        let colorLabel = new egret.TextField();
        colorLabel.textColor = 0x000000;
        colorLabel.textAlign = "center";
        colorLabel.text = text;
        colorLabel.size = 24;
        colorLabel.y = 80;
        colorLabel.x = 15;
        panel.addChild(colorLabel);    
    }

}
